"""Credential metrics."""

import argparse

from cki_lib import misc
import prometheus_client

from . import all_tokens  # noqa: F401, pylint: disable=unused-import
from . import secrets
from . import token


def process() -> str:
    """Return token metrics."""
    registry = prometheus_client.CollectorRegistry()
    metric_created_at = prometheus_client.Gauge(
        'cki_token_created_at',  'timestamp when a token was created',
        ['name', 'token_type', 'active', 'deployed'], registry=registry,
    )
    metric_expires_at = prometheus_client.Gauge(
        'cki_token_expires_at', 'timestamp when validity of token ends',
        ['name', 'token_type', 'active', 'deployed'], registry=registry,
    )

    for token_name, data in secrets.read_secrets_file().items():
        token_type = misc.get_nested_key(data, 'meta/token_type')
        active = misc.booltostr(misc.get_nested_key(data, 'meta/active', True))
        deployed = misc.booltostr(misc.get_nested_key(data, 'meta/deployed', True))
        created_at = misc.get_nested_key(data, 'meta/created_at')
        expires_at = misc.get_nested_key(data, 'meta/expires_at')

        if created_at and token_type in token.TOKEN_REGISTRY:
            metric_created_at.labels(
                token_name, token_type, active, deployed
            ).set(misc.datetime_fromisoformat_tz_utc(created_at).timestamp())
        if expires_at:
            metric_expires_at.labels(
                token_name, token_type, active, deployed
            ).set(misc.datetime_fromisoformat_tz_utc(expires_at).timestamp())
    return prometheus_client.generate_latest(registry).decode('utf8')


def main(args: list[str] | None = None) -> None:
    """Run main loop."""
    parser = argparse.ArgumentParser(description='Print Prometheus metrics about secrets')
    parser.parse_args(args)

    print(process().strip())


if __name__ == '__main__':
    main()
